package com.atguigu.java;

import org.junit.Test;

import java.util.Random;

/**
 * 通过反射创建对应的运行时类的对象
 */
public class NewInstanceTest {

    @Test
    public void test() throws Exception {
        Class<Person> clazz = Person.class;
        /*
        newInstance():调用此方法,创建对应的运行时类的对象,内部调用了空参构造器
        必须提供空参构造器,权限不能为private
         */
        Person o = clazz.newInstance();
        System.out.println(o);
    }

    @Test
    public void test2() throws Exception {
        int i = new Random().nextInt(3);
        String classPath = "";
        switch (i) {
            case 0:
                classPath = "java.util.Date";
                break;
            case 1:
                classPath = "java.lang.Object";
                break;
            case 2:
                classPath = "com.atguigu.java.Person";
                break;
        }

        Object instance = getInstance(classPath);
        System.out.println(instance);
    }


    /**
     * 创建一个指定类的对象
     *
     * @param classPath 指定类的全类名
     * @return
     * @throws Exception
     */
    public Object getInstance(String classPath) throws Exception {
        Class aClass = Class.forName(classPath);
        return aClass.newInstance();
    }
}
